/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.cache.DictCache;
import org.springblade.common.constant.MaintenanceSmsConstant;
import org.springblade.common.constant.TemplateMsgConstant;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.*;
import org.springblade.modules.admin.vo.MaintainPlanStatisticsVO;
import org.springblade.modules.admin.entity.*;
import org.springblade.modules.admin.enums.MaintainPlanContentEnum;
import org.springblade.modules.admin.enums.TaskStatusEnum;
import org.springblade.modules.admin.mapper.MaintainPlanContentMapper;
import org.springblade.modules.admin.service.*;
import org.springblade.modules.admin.utils.AsyncUtils;
import org.springblade.modules.admin.vo.*;
import org.springblade.modules.admin.mapper.MaintainPlanCheckMapper;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.modules.admin.vo.MaintainPlanPageVO;
import org.springblade.modules.admin.vo.MalFunctionHistoryVO;
import org.springblade.modules.admin.vo.PlanContentWorkDetailCommonVo;
import org.springblade.modules.admin.vo.check.ProblemPlanVo;
import org.springblade.modules.admin.vo.check.ProblemResultVo;
import org.springblade.modules.admin.vo.check.ProblemSearchVo;
import org.springblade.modules.admin.vo.check.ProblemStatusVo;
import org.springblade.modules.admin.vo.plan.CheckChildPlanVo;
import org.springblade.modules.admin.vo.plan.MaintainLogStatusVo;
import org.springblade.modules.admin.vo.plan.PlanMaintainUserVO;
import org.springblade.modules.admin.vo.plan.PlanUserSignDetailVo;
import org.springblade.modules.admin.vo.user.UserAffairAndCheckVo;
import org.springblade.modules.resource.utils.SmsUtil;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.system.vo.SimpleUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static org.springblade.modules.admin.service.BuildingService.PROJECT_TYPE_CODE;

/**
 * 质检工单表 服务实现类
 *
 * @author ysq
 * @since 2023-11-27
 */
@Service
@Slf4j
public class MaintainPlanCheckServiceImpl extends BaseServiceImpl<MaintainPlanCheckMapper, MaintainPlanCheck> implements IMaintainPlanCheckService {


	@Autowired
	@Lazy
	private IMaintainPlanContentService maintainPlanContentService;

	@Autowired
	private IMaintainPlanContentExtService maintainPlanContentExtService;

	@Autowired
	private IUserService userService;

	@Autowired
	private IMaintainPlanContentUserService maintainPlanContentUserService;

	@Autowired
	private MaintainMalfunctionLogService malfunctionLogService;

	@Autowired
	private MaintainPlanContentMapper maintainPlanContentMapper;

	@Autowired
	private IMaintainSignService maintainSignService;

	@Autowired
	private IMaintainSignService signService;

	@Autowired
	private IMaintainMalfunctionHistoryService malfunctionHistoryService;

	@Autowired
	private ElevatorService elevatorService;

	@Autowired
	private AsyncUtils asyncUtils;

	@Autowired
	private WeChatDialogueService weChatDialogueService;

	@Autowired
	private IWxFaultTypeService wxFaultTypeService;
	@Autowired
	private IWxFaultCauseService wxFaultCauseService;

	@Override
	public IPage<MaintainPlanCheckVO> selectMaintainPlanCheckPage(IPage<MaintainPlanCheckVO> page, MaintainPlanCheckVO maintainPlanCheck) {
		return page.setRecords(baseMapper.selectMaintainPlanCheckPage(page, maintainPlanCheck));
	}

	/**
	 * 新增质检工单
	 * 优先级1：新增质检工单、拓展表、详情、分配人员。与事务工单基本一致
	 *
	 * @param maintainPlanCheckBatchDTO 质检工单批量新增DTO
	 * @return 是否新增成功
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Long addBatch(MaintainPlanCheckBatchDTO maintainPlanCheckBatchDTO) {
		// 0. 初始化返回值、发送消息所需中间值
		Long resultId = null;
		String address = "";

		// 1. 获取所需数据:操作人、所需分配人员、电梯id列表、质检工单planCheck表所需数据
		Long executorUserId = AuthUtil.getUserId();
		// 操作人
		String executor = userService.getById(executorUserId).getRealName();
		// 所需分配人员 id 列表
		List<Long> userIds = maintainPlanCheckBatchDTO.getUserIds();
		// 电梯id列表
		List<Long> elevatorIds = maintainPlanCheckBatchDTO.getElevatorIds();

		// 2.遍历电梯id列表，执行新增工单、拓展表、详情、分配人员、任务追踪操作，由于人员与电梯是多对多关系，嵌套遍历，时间复杂度O(n^2)
		for (Long elevatorId : elevatorIds) {
			// 具体入库参数准备，planId
			Long planId = null;
			// 质检工单planCheck表所需数据
			MaintainPlanCheck maintainPlanCheck = new MaintainPlanCheck();
			// 是否通过、紧急程度、工单描述、附件、word文档url， 注意附件和word文档url要进行json格式化
			maintainPlanCheck.setCheckStatus(maintainPlanCheckBatchDTO.getCheckStatus());
			maintainPlanCheck.setEmerProcType(maintainPlanCheckBatchDTO.getEmerProcType());
			maintainPlanCheck.setPlanDesc(maintainPlanCheckBatchDTO.getPlanDesc());
			maintainPlanCheck.setCheckType(maintainPlanCheckBatchDTO.getCheckType());
			maintainPlanCheck.setOtherUrl(mapListToJson(maintainPlanCheckBatchDTO.getOtherUrl()));
			maintainPlanCheck.setExtWordUrl(mapListToJson(maintainPlanCheckBatchDTO.getExtWordUrl()));

			// 2.1 工单主表
			MaintainPlanContent maintainPlanContent = new MaintainPlanContent();
			// 依次赋 工单类型、计划日期、电梯id、工单状态,并插入
			maintainPlanContent.setTypeStatus(MaintainPlanContentEnum.MAINTAIN_CHECK.getId());
			maintainPlanContent.setPlanDate(maintainPlanCheckBatchDTO.getPlanDate());
			maintainPlanContent.setElevatorId(elevatorId);
			Integer status = userIds.size() > 0
				? TaskStatusEnum.ZJ_TO_START.getStatus()
				: TaskStatusEnum.ZJ_ALLOCATION.getStatus();
			maintainPlanContent.setStatus(status);
			maintainPlanContentService.save(maintainPlanContent);
			// 获取工单id
			planId = maintainPlanContent.getId();
			if (elevatorIds.size() == 1) {
				resultId = planId;
			}

			// 2.2 工单拓展表
			MaintainPlanContentExt maintainPlanContentExt = new MaintainPlanContentExt();
			maintainPlanContentExt.setPlanId(planId);
			maintainPlanContentExtService.save(maintainPlanContentExt);

			// 2.3 质检信息
			maintainPlanCheck.setPlanId(planId);
			this.save(maintainPlanCheck);

			// 2.4 遍历人员列表，分配人员
			for (Long userId : userIds) {
				MaintainPlanContentUser maintainPlanContentUser = new MaintainPlanContentUser();
				maintainPlanContentUser.setUserId(userId);
				maintainPlanContentUser.setPlanId(maintainPlanContent.getId());
				PlanUserSignDetailVo planUserSignDetailVo = new PlanUserSignDetailVo();
				planUserSignDetailVo.setUserName(userService.getById(userId).getRealName());
				planUserSignDetailVo.setPlanId(maintainPlanContent.getId());
				maintainPlanContentUser.setSignInfo(JSON.toJSONString(planUserSignDetailVo));
				maintainPlanContentUserService.save(maintainPlanContentUser);
			}

			// 2.5 每个工单日志追踪
			// 创建工单追踪日志
			MaintainMalfunctionLog maintainMalfunctionLog = new MaintainMalfunctionLog();
			maintainMalfunctionLog.setPlanStatus(TaskStatusEnum.ZJ_ALLOCATION.getStatus());
			maintainMalfunctionLog.setPlanId(maintainPlanContent.getId());
			maintainMalfunctionLog.setExecutor(executor);
			maintainMalfunctionLog.setTypeName("创建工单");
			malfunctionLogService.save(maintainMalfunctionLog);
			// 指派人员追踪日志
			if (userIds.size() > 0) {
				List<String> userNames = userService.listByIds(maintainPlanCheckBatchDTO.getUserIds())
					.stream()
					.map(User::getRealName)
					.distinct()
					.collect(Collectors.toList());
				MaintainMalfunctionLog sendLog = new MaintainMalfunctionLog();
				sendLog.setPlanId(maintainPlanContent.getId());
				sendLog.setPlanStatus(TaskStatusEnum.ZJ_TO_START.getStatus());
				sendLog.setExecutor(executor);
				sendLog.setTypeName("分配人员[" + String.join("/", userNames) + "]");
				sendLog.setUserNames(String.join("/", userNames));
				malfunctionLogService.save(sendLog);
			}
		}
		// 3. 发送消息
		// 3.1 获取地址
		for (Long elevatorId : elevatorIds) {
			ElevatorVO elevatorVO = elevatorService.selectElevator(elevatorId);
			if (StrUtil.isEmpty(address)) {
				address = address + elevatorVO.getBuildingName() + "-" + elevatorVO.getElevatorAddress();
			} else {
				address = address + "," + elevatorVO.getBuildingName() + "-" + elevatorVO.getElevatorAddress();
			}
		}
		sendSaveMessage(userIds, executor, maintainPlanCheckBatchDTO.getPlanDesc(), address, maintainPlanCheckBatchDTO.getCheckType());

		return resultId;
	}

	/**
	 * 根据工单id查询质检工单详情
	 * 优先级1 与事务工单详情基本一致
	 *
	 * @param planId 工单id
	 * @return 工单详情
	 */
	@Override
	public MaintainPlanCheckVO selectMaintainPlanDetailById(Long planId) {
		// 0. 初始化返回值
		MaintainPlanCheckVO maintainPlanCheckVO = new MaintainPlanCheckVO();
		MaintainPlanContent maintainPlanContent = maintainPlanContentService.getById(planId);

		// 1. 获取任务基础信息 PlanContentWorkDetailCommonVo
		PlanContentWorkDetailCommonVo planContentWorkDetailCommonVo = maintainPlanContentMapper.workDetail(planId);
		planContentWorkDetailCommonVo.setBuildingTypeName(DictCache.getValue(PROJECT_TYPE_CODE, planContentWorkDetailCommonVo.getBuildingType()));
		maintainPlanCheckVO.setPlanContentWorkDetailCommonVo(planContentWorkDetailCommonVo);

		// 获取任务计划时间
		maintainPlanCheckVO.setPlanDate(maintainPlanContent.getPlanDate());

		// 2. 获取人员信息
		List<PlanMaintainUserVO> maintainUserList = maintainPlanContentUserService.selectWorkUsers(planId);
		maintainUserList = maintainUserList.stream().filter(e -> {
			Integer userSignCount = signService.count(Wrappers.<MaintainSign>lambdaQuery().eq(MaintainSign::getPlanId, e.getPlanId()).eq(MaintainSign::getUserId, e.getMaintainUserId()));
			e.setUserSignCount(userSignCount);
			if (maintainPlanContent.getStatus().equals(TaskStatusEnum.BY_FINISH.getStatus()) && maintainPlanContent.getTypeStatus().equals(MaintainPlanContentEnum.MAINTAIN_BY.getId())) {
				return userSignCount > 0;
			} else if (maintainPlanContent.getStatus().equals(TaskStatusEnum.WX_SIGN_FINISH.getStatus()) && maintainPlanContent.getTypeStatus().equals(MaintainPlanContentEnum.MAINTAIN_WX.getId())) {
				return userSignCount > 0;
			} else {
				return true;
			}
		}).collect(Collectors.toList());

		// 前端任务转派删除规制字段返回值:是否存在过签到字段
		for (PlanMaintainUserVO planMaintainUserVO : maintainUserList) {
			Long userId = planMaintainUserVO.getMaintainUserId();
			int isExist = signService.list(new LambdaQueryWrapper<MaintainSign>()
				.eq(MaintainSign::getPlanId, planId)
				.eq(MaintainSign::getUserId, userId)
				.eq(BaseEntity::getIsDeleted, 0)
			).size();
			if (isExist > 0) {
				planMaintainUserVO.setIsSigned(1);
			} else {
				planMaintainUserVO.setIsSigned(0);
			}
		}
		maintainPlanCheckVO.setMaintainUserList(maintainUserList);

		// 3. 获取工单追踪日志信息
		List<MaintainMalfunctionLog> logList = malfunctionLogService.list(
			Wrappers.<MaintainMalfunctionLog>lambdaQuery()
				.eq(MaintainMalfunctionLog::getPlanId, planId));
		maintainPlanCheckVO.setLogList(logList);

		// 4. 获取追踪状态
		List<MaintainLogStatusVo> maintainLogStatusVos = malfunctionLogService.logStatusList(planId);
		for (MaintainLogStatusVo maintainLogStatusVo : maintainLogStatusVos) {
			String taskName = TaskStatusEnum.getTaskName(MaintainPlanContentEnum.MAINTAIN_AFFAIR.getId(), maintainLogStatusVo.getPlanStatus());
			maintainLogStatusVo.setPlanStatusName(taskName);
		}
		maintainPlanCheckVO.setStatusVos(maintainLogStatusVos);

		// 5. 获取故障历史
		List<MalFunctionHistoryVO> malFunctionHistories = malfunctionHistoryService.selectByPlanId(planId);

		// 6. 获取质检信息
		MaintainPlanCheck maintainPlanCheck = this.getOne(
			Wrappers.<MaintainPlanCheck>lambdaQuery()
				.eq(MaintainPlanCheck::getPlanId, planId));
		// 6.1 获取附件
		String otherUrl = maintainPlanCheck.getOtherUrl();
		List<Map<String, String>> otherUrlList = jsonToMapList(otherUrl);
		maintainPlanCheckVO.setOtherUrlList(otherUrlList);
		String extWordUrl = maintainPlanCheck.getExtWordUrl();
		List<Map<String, String>> extWordUrlList = jsonToMapList(extWordUrl);
		maintainPlanCheckVO.setExtWordUrlList(extWordUrlList);
		maintainPlanCheck.setPlanDate(maintainPlanContent.getPlanDate());
		maintainPlanCheckVO.setMaintainPlanCheck(maintainPlanCheck);

		// 7. 优先级2对详情信息进行补充以及调整
//		Integer checkStatus = 2;
//		if (checkStatus.equals(maintainPlanCheck.getCheckStatus())) {
//			for (MalFunctionHistoryVO maintainMalfunctionHistory : malFunctionHistories) {
//				if (maintainMalfunctionHistory.getChildPlanId() != null) {
//					maintainMalfunctionHistory.setCheckChildPlan(getCheckChildPlanVo(maintainMalfunctionHistory.getChildPlanId()));
//				}
//			}
//		}
		if (Func.isNotEmpty(malFunctionHistories)) {
			Map<Long, List<WxFaultType>> wxFaultTypeMap = wxFaultTypeService.list().stream().collect(Collectors.groupingBy(WxFaultType::getId));
			Map<Long, List<WxFaultCause>> wxFaultCauseMap = wxFaultCauseService.list().stream().collect(Collectors.groupingBy(WxFaultCause::getId));
			for (MalFunctionHistoryVO maintainMalfunctionHistory : malFunctionHistories) {
				if (maintainMalfunctionHistory.getChildPlanId() != null) {
					maintainMalfunctionHistory.setCheckChildPlan(getCheckChildPlanVo(maintainMalfunctionHistory.getChildPlanId()));
				}
				//封装维修原因
				List<String> names0 = new ArrayList<>(16);
				if (StrUtil.isNotEmpty(maintainMalfunctionHistory.getFaultReasonKey())) {
					List<String> list = Func.toStrList(maintainMalfunctionHistory.getFaultReasonKey());
					for (String id : list) {
						List<WxFaultCause> wxFaultTypes = wxFaultCauseMap.get(Convert.toLong(id));
						if (wxFaultTypes != null && wxFaultTypes.size() > 0) {
							names0.add(wxFaultTypes.get(0).getFaultName());
						}
					}
					if (names0.contains("其他")) {
						names0.remove("其他");
						names0.add("其他");
						maintainMalfunctionHistory.setFaultReasonName(String.join(",", names0) + "-" + maintainMalfunctionHistory.getFaultReasonName());
					} else {
						maintainMalfunctionHistory.setFaultReasonName(String.join(",", names0));
					}
				}

				//封装维修责任
				List<String> names1 = new ArrayList<>(16);
				if (StrUtil.isNotEmpty(maintainMalfunctionHistory.getFaultReasonWhoKey())) {
					List<String> list = Func.toStrList(maintainMalfunctionHistory.getFaultReasonWhoKey());
					for (String id : list) {
						List<WxFaultType> wxFaultTypes = wxFaultTypeMap.get(Convert.toLong(id));
						if (wxFaultTypes != null && wxFaultTypes.size() > 0) {
							names1.add(wxFaultTypes.get(0).getName());
						}
					}
					if (names1.contains("其他")) {
						names1.remove("其他");
						names1.add("其他");
						maintainMalfunctionHistory.setFaultReasonWhoName(String.join(",", names1) + "-" + maintainMalfunctionHistory.getFaultReasonWhoName());
					} else {
						maintainMalfunctionHistory.setFaultReasonWhoName(String.join(",", names1));
					}
				}

			}
		}
		maintainPlanCheckVO.setMalFunctionHistories(malFunctionHistories);
		return maintainPlanCheckVO;
	}


	@Override
	public IPage<MaintainPlanPageVO> pageByCondition(MaintainPlanCheckPageDTO maintainPlanCheckDTO) {
		// 1. 获取分页参数
		Query query = new Query();
		query.setSize(maintainPlanCheckDTO.getSize());
		query.setCurrent(maintainPlanCheckDTO.getCurrent());
		IPage<MaintainPlanPageVO> page = Condition.getPage(query);
		// 2. 根据条件查询
		List<Integer> planStatuss = new ArrayList<>(5);
		//离职人员获取工单信息
		if (maintainPlanCheckDTO.getIsUserStatus() != null) {
			if (maintainPlanCheckDTO.getPlanStatus() == null) {
				planStatuss.add(TaskStatusEnum.ZJ_TO_START.getStatus());
				planStatuss.add(TaskStatusEnum.ZJ_UNDER_WAY.getStatus());
			} else {
				planStatuss.add(maintainPlanCheckDTO.getPlanStatus());
			}
		}
		if (maintainPlanCheckDTO.getPlanStatus() != null) {
			planStatuss.add(maintainPlanCheckDTO.getPlanStatus());
		}
		if (planStatuss.size() > 0) {
			maintainPlanCheckDTO.setPlanStatuss(planStatuss);
		}
		List<MaintainPlanPageVO> maintainPlanPageVOS = baseMapper.pageByCondition(page, maintainPlanCheckDTO);
		// 3. 封装并返回
		page.setRecords(maintainPlanPageVOS);
		return page;
	}

	@Override
	public MaintainPlanStatisticsVO statistics() {
		// 直接查询并赋值
		return baseMapper.statistics();
	}

	@Override
	public List<MaintainPlanPageVO> listByCondition(MaintainPlanCheckPageDTO maintainPlanCheckDTO) {
		return baseMapper.listByCondition(maintainPlanCheckDTO);
	}

	/**
	 * 质检工单批量关闭
	 *
	 * @param checkPlanCloseDTO 关闭入参
	 * @return 是否成功
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean closeBatch(CheckPlanCloseDTO checkPlanCloseDTO) {
		List<Long> planIds = checkPlanCloseDTO.getPlanIds();
		List<MaintainPlanContent> targetList = maintainPlanContentService.list(new LambdaQueryWrapper<MaintainPlanContent>()
			.in(BaseEntity::getId, planIds)
		);
		// 增加工单限制
		targetList.forEach(
			t -> {
				Integer status = t.getStatus();
				if (status.equals(TaskStatusEnum.ZJ_UNDER_WAY.getStatus())
					|| status.equals(TaskStatusEnum.ZJ_SIGN_FINISH.getStatus())) {
					throw new ServiceException("业务异常！不允许关闭进行中、已完成的工单！请重新选择");
				}
			}
		);
		targetList.forEach(t -> t.setStatus(TaskStatusEnum.ZJ_CLOSED.getStatus()));
		// 更新任务追踪状态
		List<MaintainMalfunctionLog> updateList = new ArrayList<>();
		Long executorId = AuthUtil.getUserId();
		String executor = userService.getById(executorId).getRealName();
		for (Long planId : planIds) {
			MaintainMalfunctionLog maintainMalfunctionLog = new MaintainMalfunctionLog();
			maintainMalfunctionLog.setPlanId(planId);
			maintainMalfunctionLog.setPlanStatus(TaskStatusEnum.ZJ_CLOSED.getStatus());
			maintainMalfunctionLog.setExecutor(executor);
			maintainMalfunctionLog.setTypeName("关闭工单");
			updateList.add(maintainMalfunctionLog);
		}
		malfunctionLogService.saveBatch(updateList);
		return maintainPlanContentService.updateBatchById(targetList);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean setExecuteTime(CheckPlanSetTimeDTO checkPlanSetTimeDTO) {
		Date planDate = checkPlanSetTimeDTO.getPlanDate();
		List<Long> planIds = checkPlanSetTimeDTO.getPlanIds();
		List<MaintainPlanContent> planContentList = maintainPlanContentService.listByIds(planIds);
		// 增加工单限制
		planContentList.forEach(
			t -> {
				Integer status = t.getStatus();
				if (status.equals(TaskStatusEnum.ZJ_UNDER_WAY.getStatus())
					|| status.equals(TaskStatusEnum.ZJ_SIGN_FINISH.getStatus())
					|| status.equals(TaskStatusEnum.ZJ_CLOSED.getStatus())
				) {
					throw new ServiceException("业务异常！不允许修改进行中、已完成、已关闭的工单时间！请重新选择");
				}
			}
		);
		if (!Func.isNull(planDate)) {
			for (MaintainPlanContent maintainPlanContent : planContentList) {
				maintainPlanContent.setPlanDate(planDate);
			}
		}
		return maintainPlanContentService.updateBatchById(planContentList);
	}

	@Override
	public List<CheckChildPlanVo> getCheckChildPlanList(Long planId, Integer typeStatus) {
		MaintainPlanCheck maintainPlanCheck = this.getOne(Wrappers.<MaintainPlanCheck>lambdaQuery().eq(MaintainPlanCheck::getPlanId, planId));
		//表示通过
		// 2024-05-08 需求变更，通过的情况也返回，以下代码注释
//		Integer checkStatus = 1;
//		if (checkStatus.equals(maintainPlanCheck.getCheckStatus())) {
//			return new ArrayList<>();
//		}
		List<CheckChildPlanVo> checkChildPlanList = baseMapper.getCheckChildPlanList(planId, typeStatus);
		for (CheckChildPlanVo checkChildPlanVo : checkChildPlanList) {
			checkChildPlanVo.setStatusName(TaskStatusEnum.getTaskName(checkChildPlanVo.getTypeStatus(), checkChildPlanVo.getStatus()));
		}
		return checkChildPlanList;
	}

	@Override
	public IPage<ProblemResultVo> getProblemResultList(ProblemSearchVo problemSearchVo) {

		Map<Long, List<WxFaultType>> wxFaultTypeMap = wxFaultTypeService.list().stream().collect(Collectors.groupingBy(WxFaultType::getId));
		Map<Long, List<WxFaultCause>> wxFaultCauseMap = wxFaultCauseService.list().stream().collect(Collectors.groupingBy(WxFaultCause::getId));

		Query query = new Query();
		query.setSize(problemSearchVo.getSize());
		query.setCurrent(problemSearchVo.getCurrent());
		IPage<ProblemResultVo> page = Condition.getPage(query);
		List<ProblemResultVo> list = baseMapper.getProblemResultList(page, problemSearchVo);
		for (ProblemResultVo problemResultVo : list) {
			List<ProblemPlanVo> list1 = baseMapper.getMalfHistory(problemResultVo.getMalHistoryIds());
			List<ProblemPlanVo> planVos = list1.stream().filter(o -> o.getChildPlanId() == null).collect(Collectors.toList());
			problemResultVo.setProblemCounts(list1.size());
			problemResultVo.setDisProblemCounts(planVos.size());
			problemResultVo.setEnProblemCounts(problemResultVo.getProblemCounts() - problemResultVo.getDisProblemCounts());
			for (ProblemPlanVo problemPlanVo : list1) {
				if (problemPlanVo.getTypeStatus() != null) {
					problemPlanVo.setPlanStatusName(TaskStatusEnum.getTaskName(problemPlanVo.getTypeStatus(), problemPlanVo.getPlanStatus()));
				}
				List<String> wxFaultIds = problemPlanVo.getWxFaultIds();
				List<String> names1 = new ArrayList<>(16);
				if (wxFaultIds != null && wxFaultIds.size() > 0) {
					for (String wxFaultId : wxFaultIds) {
						List<WxFaultCause> wxFaultCauses = wxFaultCauseMap.get(Convert.toLong(wxFaultId));
						if (wxFaultCauses != null && wxFaultCauses.size() > 0) {
							names1.add(wxFaultCauses.get(0).getFaultName());
						}
					}
					if (names1.contains("其他")) {
						names1.remove("其他");
						names1.add("其他");
						problemPlanVo.setFaultReasonName(String.join(",", names1) + "-" + problemPlanVo.getFaultReasonName());
					} else {
						problemPlanVo.setFaultReasonName(String.join(",", names1));
					}
				}

				List<String> names2 = new ArrayList<>(16);
				List<String> wxTypeIds = problemPlanVo.getWxTypeIds();
				if (wxTypeIds != null && wxTypeIds.size() > 0) {
					for (String wxTypeId : wxTypeIds) {
						List<WxFaultType> wxFaultTypes = wxFaultTypeMap.get(Convert.toLong(wxTypeId));
						if (wxFaultTypes != null && wxFaultTypes.size() > 0) {
							names2.add(wxFaultTypes.get(0).getName());
						}
					}
					if (names2.contains("其他")) {
						names2.remove("其他");
						names2.add("其他");
						problemPlanVo.setFaultReasonWhoName(String.join(",", names2) + "-" + problemPlanVo.getFaultReasonWhoName());
					} else {
						problemPlanVo.setFaultReasonWhoName(String.join(",", names2));
					}
				}
			}
			problemResultVo.setList(list1);
		}
		page.setRecords(list);
		return page;
	}

	@Override
	public ProblemStatusVo getProblemStatus() {

		ProblemStatusVo problemStatusVo = new ProblemStatusVo();
		List<MaintainMalfunctionHistory> list = baseMapper.getProblemStatus();
		int size = list.stream().filter(o -> o.getChildPlanId() == null).collect(Collectors.toList()).size();
		problemStatusVo.setDisStatusCounts(size);
		problemStatusVo.setAllStatusCounts(list.size());
		problemStatusVo.setEnStatusCounts(list.size() - size);
		return problemStatusVo;
	}

	/**
	 * 质检工单批量指派/转派
	 *
	 * @param checkPlanSendDTO 指派/转派入参
	 * @return 是否成功
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean assign(CheckPlanSendDTO checkPlanSendDTO) {
		// 1. 获取所需数据:工单id列表, 用户id列表,日期
		List<Long> planIds = checkPlanSendDTO.getPlanIds();
		List<Long> userIds = checkPlanSendDTO.getUserIds();
		Date planDate = checkPlanSendDTO.getPlanDate();
		// 即将发送消息/入库的列表
		List<MaintainPlanContentUser> sendList = new ArrayList<>();
		// 日期为立即执行时，获取当前时间
		if (Func.isNull(planDate)) {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String todayString = dateFormat.format(new Date());
			Date today = null;
			try {
				today = dateFormat.parse(todayString);
			} catch (Exception e) {
				e.printStackTrace();
			}
			planDate = today;
		}

		/*
		 * 2. 遍历planIds列表, 嵌套遍历userIds列表, 时间复杂度O(n^2)
		 * 遍历工单列表, 查看状态:
		 * 待分配 -> 插入操作,分配, 给所有人发消息, 更新工单状态：待分配 -> 待开始, 更新任务追踪状态;
		 * 待开始 -> 可增删改人员, 逻辑删表数据、给新增的人发消息,更新任务追踪状态;
		 * 进行中 -> 只增不删, 给新增的人发消息,更新任务追踪状态;
		 */
		for (Long planId : planIds) {
			MaintainPlanContent currentPlan = maintainPlanContentService.getById(planId);
			currentPlan.setPlanDate(planDate);
			// 待开始
			if (currentPlan.getStatus().equals(TaskStatusEnum.ZJ_TO_START.getStatus())) {
				transferNotStarted(planId, planDate, userIds, sendList, currentPlan);
				sendList = new ArrayList<>();
			}
			// 进行中
			else if (currentPlan.getStatus().equals(TaskStatusEnum.ZJ_UNDER_WAY.getStatus())) {
				transferStarted(planId, planDate, userIds, sendList, currentPlan);
				sendList = new ArrayList<>();
			}
			// 待分配, 由于分配状态会更改, 更改后会命中后续状态, 放到循环尾部
			else if (currentPlan.getStatus().equals(TaskStatusEnum.ZJ_ALLOCATION.getStatus())) {
				sendToUsers(planId, planDate, userIds, sendList, currentPlan);
				sendList = new ArrayList<>();
			}
		}
		// 改为按人、工单只发1次
		for (Long userId : userIds) {
			MaintainPlanContentUser maintainPlanContentUser = new MaintainPlanContentUser();
			User user = userService.getById(userId);
			maintainPlanContentUser.setUserName(user.getRealName());
			maintainPlanContentUser.setUserId(userId);
			maintainPlanContentUser.setPlanDate(planDate);
			sendList.add(maintainPlanContentUser);
		}
		sendMessage(sendList, planIds);

		return Boolean.TRUE;
	}


	/**
	 * 质检工单-未开始-转派
	 *
	 * @param planId   当前工单id
	 * @param planDate 计划日期
	 * @param userIds  用户id集合
	 * @param sendList 发送消息日期
	 */
	private void transferNotStarted(Long planId,
									Date planDate,
									List<Long> userIds,
									List<MaintainPlanContentUser> sendList,
									MaintainPlanContent currentPlan) {

		Map<String, List<Long>> diff = getDiff(planId, userIds);
		List<Long> preDeleteList = diff.get("preDeleteList");
		List<Long> preAddList = diff.get("preAddList");

		// 执行删除
		if (Func.isNotEmpty(preDeleteList)) {
			List<MaintainPlanContentUser> deletedTargets = new ArrayList<>();
			for (Long preDeleteUserId : preDeleteList) {
				List<MaintainPlanContentUser> tempDelList = maintainPlanContentUserService.list(new LambdaQueryWrapper<MaintainPlanContentUser>()
					.eq(MaintainPlanContentUser::getPlanId, planId)
					.eq(MaintainPlanContentUser::getUserId, preDeleteUserId)
					.eq(BaseEntity::getIsDeleted, 0)
				);
				deletedTargets.addAll(tempDelList);
			}
			if (Func.isNotEmpty(deletedTargets)) {
				maintainPlanContentUserService.removeByIds(deletedTargets.stream().map(BaseEntity::getId).collect(Collectors.toList()));
			}

		}

		// 执行新增
		if (Func.isNotEmpty(preAddList)) {
			for (Long userId : preAddList) {
				MaintainPlanContentUser maintainPlanContentUser = sendElement(userId, planId, planDate);
				sendList.add(maintainPlanContentUser);
			}
		}
		// 入库
		maintainPlanContentUserService.saveBatch(sendList);
		// 更新任务追踪状态
		updateWorkMalfunctionLog(planId, sendList, currentPlan.getStatus());
	}

	/**
	 * 质检工单-已开始-转派
	 *
	 * @param planId   当前工单id
	 * @param planDate 计划时间
	 * @param userIds  用户id
	 * @param sendList 发送消息列表
	 */
	private void transferStarted(Long planId,
								 Date planDate,
								 List<Long> userIds,
								 List<MaintainPlanContentUser> sendList,
								 MaintainPlanContent currentPlan) {
		Map<String, List<Long>> diff = getDiff(planId, userIds);
		List<Long> preDeleteList = diff.get("preDeleteList");
		// 根据已选删除列表判断是否存在签到信息，存在：抛异常; 不存在，删除
		if (Func.isNotEmpty(preDeleteList)) {
			preDeleteList.forEach(f -> {
				int isSign = maintainSignService.list(new LambdaQueryWrapper<MaintainSign>()
					.eq(MaintainSign::getPlanId, planId)
					.eq(MaintainSign::getUserId, f)
					.eq(BaseEntity::getIsDeleted, 0)
				).size();
				if (isSign > 0) {
					throw new ServiceException("业务异常！无法删除已签到的派遣人，请重新选择");
				}
			});
			for (int i = 0; i < preDeleteList.size(); i++) {
				MaintainPlanContentUser removeTarget = maintainPlanContentUserService.getOne(new LambdaQueryWrapper<MaintainPlanContentUser>()
					.eq(MaintainPlanContentUser::getUserId, preDeleteList.get(i))
					.eq(MaintainPlanContentUser::getPlanId, planId)
					.eq(BaseEntity::getIsDeleted, 0)
				);
				maintainPlanContentUserService.removeById(removeTarget.getId());
			}
		}
		// 根据当前 工单id 判断是否已有记录, 是：不执行； 否：指派
		for (Long userId : userIds) {
			int existSize = maintainPlanContentUserService.list(new LambdaQueryWrapper<MaintainPlanContentUser>()
				.eq(MaintainPlanContentUser::getPlanId, planId)
				.eq(MaintainPlanContentUser::getUserId, userId)
				.eq(BaseEntity::getIsDeleted, 0)
			).size();
			if (existSize > 0) {
				continue;
			}
			MaintainPlanContentUser maintainPlanContentUser = sendElement(userId, planId, planDate);
			sendList.add(maintainPlanContentUser);
		}
		// 入库
		maintainPlanContentUserService.saveBatch(sendList);
		// 更新任务追踪状态
		updateWorkMalfunctionLog(planId, sendList, currentPlan.getStatus());
	}

	/**
	 * 质检工单-指派
	 *
	 * @param planId      当前工单 id
	 * @param planDate    工单日期
	 * @param userIds     批量用户列表
	 * @param sendList    发送消息列表
	 * @param currentPlan 当前工单
	 */
	private void sendToUsers(Long planId,
							 Date planDate,
							 List<Long> userIds,
							 List<MaintainPlanContentUser> sendList,
							 MaintainPlanContent currentPlan) {
		// 已指派去重
		List<Long> existList = maintainPlanContentUserService.list(new LambdaQueryWrapper<MaintainPlanContentUser>()
			.eq(MaintainPlanContentUser::getPlanId, planId)
			.eq(BaseEntity::getIsDeleted, 0)
		).stream().map(MaintainPlanContentUser::getUserId).collect(Collectors.toList());

		if (Func.isNotEmpty(existList)) {
			userIds = userIds.stream().filter(f -> !existList.contains(f)).collect(Collectors.toList());
		}
		if (Func.isNotEmpty(userIds)) {
			// 指派
			for (Long userId : userIds) {
				MaintainPlanContentUser maintainPlanContentUser = sendElement(userId, planId, planDate);
				sendList.add(maintainPlanContentUser);
			}
			// 入库
			maintainPlanContentUserService.saveBatch(sendList);
			// 更新当前工单状态 待分配 -> 已指派
			currentPlan.setStatus(TaskStatusEnum.SW_TO_START.getStatus());
			maintainPlanContentService.updateById(currentPlan);
			// 更新任务追踪状态, 待分配 -> 分配
			updateWorkMalfunctionLog(planId, sendList, TaskStatusEnum.SW_ALLOCATION.getStatus());
		}
	}

	/**
	 * 质检工单 指派/转派 发送 模板消息 和 短信 的方法
	 */
	private void sendMessage(List<MaintainPlanContentUser> sendList, List<Long> planIds) {
		String userName = AuthUtil.getUserName();
		// 根据工单 批量组装building、电梯信息
		String thing18 = "";
		for (Long planId : planIds) {
			MaintainPlanContent currentPlan = maintainPlanContentService.selectById(planId);
			Long elevatorId = currentPlan.getElevatorId();
			ElevatorVO elevatorVO = elevatorService.selectElevator(elevatorId);
			thing18 = thing18 + elevatorVO.getBuildingName() + "-" + elevatorVO.getElevatorAddress() + ";";
		}

		boolean confirm = Func.isNotEmpty(sendList);
		if (confirm) {
			List<Long> userIds = sendList.stream().map(MaintainPlanContentUser::getUserId).distinct().collect(Collectors.toList());
			for (Long userId : userIds) {
				SimpleUserVO assignUserInfo = userService.getSimpleUserInfo(userId);
				if (Func.isNotEmpty(assignUserInfo)) {
					if (Func.isNotEmpty(assignUserInfo.getOpenid())) {
						String skipUrl = "pages/home/index?footerKey=myTask&typeStatus=6";
						Map<String, String> templateDataMap = new HashMap<>(8);
						templateDataMap.put("first", "工单处理提醒");
						templateDataMap.put("thing10", "质量检查");
						templateDataMap.put("thing9", "电梯出现频繁故障，请检查电梯维保");
						templateDataMap.put("thing18", thing18.length() > 16 ? thing18.substring(0, 15) : thing18);
						templateDataMap.put("thing7", userName);
						templateDataMap.put("time8", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
						templateDataMap.put("remark", "请及时登录梯无忧小程序执行事务任务!");
						templateDataMap.put("params", skipUrl);
						weChatDialogueService.sendMsg(assignUserInfo.getOpenid(), TemplateMsgConstant.AFFAIR_MESSAGE, templateDataMap);
					}
					log.info("===========给事务工单执行人发送手机短信, 手机号码:[{}]===========", assignUserInfo.getUserName(), assignUserInfo.getPhone());
					Map<String, String> smsParam = new HashMap<>(2);
					smsParam.put("status", "待开始");
					SmsUtil.sendMessage(MaintenanceSmsConstant.QUALITY_MESSAGE, BladeConstant.ADMIN_TENANT_ID, smsParam, assignUserInfo.getPhone());
				}
			}
		}
	}

	/**
	 * 公共方法抽取
	 * 新增时发送消息
	 */
	private void sendSaveMessage(List<Long> userIds, String userName, String planDesc, String address, Integer checkType) {
		String checkTypeName = "保养质检";
		if (checkType == 1) {
			checkTypeName = "保养质检";
		} else if (checkType == 2) {
			checkTypeName = "重复故障质检";
		} else if (checkType == 3) {
			checkTypeName = "维保移交质检";
		} else if (checkType == 4) {
			checkTypeName = "安装移交质检";
		} else if (checkType == 5) {
			checkTypeName = "常规质检";
		}
		if (Func.isNotEmpty(userIds)) {
			for (Long userId : userIds) {
				SimpleUserVO assignUserInfo = userService.getSimpleUserInfo(userId);
				if (Func.isNotEmpty(assignUserInfo)) {
					if (Func.isNotEmpty(assignUserInfo.getOpenid())) {
						String skipUrl = "pages/home/index?footerKey=myTask&typeStatus=6";
						Map<String, String> templateDataMap = new HashMap<>(8);
						templateDataMap.put("first", "工单处理提醒");
						templateDataMap.put("thing10", checkTypeName);
						templateDataMap.put("thing9", planDesc);
						templateDataMap.put("thing18", address.length() > 16 ? address.substring(0, 15) : address);
						templateDataMap.put("thing7", userName);
						templateDataMap.put("time8", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
						templateDataMap.put("remark", "请及时登录梯无忧小程序执行事务任务!");
						templateDataMap.put("params", skipUrl);
						weChatDialogueService.sendMsg(assignUserInfo.getOpenid(), TemplateMsgConstant.AFFAIR_MESSAGE, templateDataMap);
					}
					log.info("===========给质检工单执行人发送手机短信, 手机号码:[{}]===========", assignUserInfo.getUserName(), assignUserInfo.getPhone());
				}
				Map<String, String> smsParam = new HashMap<>(2);
				smsParam.put("status", "待开始");
				SmsUtil.sendMessage(MaintenanceSmsConstant.QUALITY_MESSAGE, BladeConstant.ADMIN_TENANT_ID, smsParam, assignUserInfo.getPhone());
			}
		}
	}

	/**
	 * 公共方法抽取
	 *
	 * @param planId  当前工单id
	 * @param userIds 当前前端传入 userId
	 * @return 获取人员异同
	 */
	private Map<String, List<Long>> getDiff(Long planId, List<Long> userIds) {
		Map<String, List<Long>> result = new HashMap<>(2);
		// 抽取 公共 user id 列表:  当前工单与公共列表之差 -> 逻辑删 ; 入参与公共列表之差 -> 新增
		// 当前已有指派列表
		List<MaintainPlanContentUser> existList = maintainPlanContentUserService.list(new LambdaQueryWrapper<MaintainPlanContentUser>()
			.eq(MaintainPlanContentUser::getPlanId, planId)
			.eq(BaseEntity::getIsDeleted, 0)
		);
		// 求公共 id
		List<Long> existUserIds = existList
			.stream()
			.map(MaintainPlanContentUser::getUserId)
			.collect(Collectors.toList());
		List<Long> publicUserIds = new ArrayList<>();
		for (Long userId : userIds) {
			if (existUserIds.contains(userId)) {
				publicUserIds.add(userId);
			}
		}

		// 已有 id - 公共 id = 待删除的 id
		List<Long> preDeleteList = existUserIds
			.stream()
			.filter(f -> !publicUserIds.contains(f))
			.collect(Collectors.toList());

		// 入参 id - 公共 id = 待新增的 id
		List<Long> preAddList = userIds
			.stream()
			.filter(f -> !publicUserIds.contains(f))
			.collect(Collectors.toList());

		result.put("preDeleteList", preDeleteList);
		result.put("preAddList", preAddList);
		return result;
	}

	/**
	 * 公共方法抽取
	 * 循环赋值
	 */
	private MaintainPlanContentUser sendElement(Long userId, Long planId, Date planDate) {
		MaintainPlanContentUser maintainPlanContentUser = new MaintainPlanContentUser();
		maintainPlanContentUser.setPlanId(planId);
		maintainPlanContentUser.setUserId(userId);
		maintainPlanContentUser.setPlanDate(planDate);
		// 补充签到细节信息
		PlanUserSignDetailVo planUserSignDetailVo = new PlanUserSignDetailVo();
		planUserSignDetailVo.setUserName(userService.getById(userId).getRealName());
		planUserSignDetailVo.setPlanId(planId);
		maintainPlanContentUser.setSignInfo(JSON.toJSONString(planUserSignDetailVo));
		return maintainPlanContentUser;
	}


	/**
	 * 公共方法抽取
	 * 更新任务追踪状态
	 */
	private void updateWorkMalfunctionLog(Long planId, List<MaintainPlanContentUser> list, Integer planStatus) {
		// 创建任务追踪对象，获取所需数据，插入操作
		String typeName;
		if (planStatus.equals(TaskStatusEnum.SW_ALLOCATION.getStatus())) {
			typeName = "指派人员";
		} else {
			typeName = "转派人员";
		}
		Long executorId = AuthUtil.getUserId();
		String executor = userService.getById(executorId).getRealName();
		if (Func.isNotEmpty(list)) {
			List<Long> tempIds = list
				.stream()
				.map(MaintainPlanContentUser::getUserId)
				.distinct()
				.collect(Collectors.toList());

			List<Long> existList = maintainPlanContentUserService.list(new LambdaQueryWrapper<MaintainPlanContentUser>()
				.eq(MaintainPlanContentUser::getPlanId, planId)
				.eq(BaseEntity::getIsDeleted, 0)
			).stream()
				.map(MaintainPlanContentUser::getUserId)
				.collect(Collectors.toList());

			tempIds.addAll(existList);
			tempIds = tempIds.stream().distinct().collect(Collectors.toList());

			List<String> userNames = userService.listByIds(tempIds)
				.stream()
				.map(User::getRealName)
				.collect(Collectors.toList());
			MaintainMalfunctionLog maintainMalfunctionLog = new MaintainMalfunctionLog();
			maintainMalfunctionLog.setPlanId(planId);
			maintainMalfunctionLog.setPlanStatus(maintainPlanContentService.getById(planId).getStatus());
			maintainMalfunctionLog.setExecutor(executor);
			maintainMalfunctionLog.setUserNames(String.join("/", userNames));
			maintainMalfunctionLog.setTypeName(typeName + "[" + String.join("/", userNames) + "]");
			malfunctionLogService.save(maintainMalfunctionLog);
		} else {
			List<Long> existList = maintainPlanContentUserService.list(new LambdaQueryWrapper<MaintainPlanContentUser>()
				.eq(MaintainPlanContentUser::getPlanId, planId)
				.eq(BaseEntity::getIsDeleted, 0)
			).stream()
				.map(MaintainPlanContentUser::getUserId)
				.collect(Collectors.toList());
			List<String> userNames = userService.listByIds(existList)
				.stream()
				.map(User::getRealName)
				.collect(Collectors.toList());
			MaintainMalfunctionLog maintainMalfunctionLog = new MaintainMalfunctionLog();
			maintainMalfunctionLog.setPlanId(planId);
			maintainMalfunctionLog.setPlanStatus(maintainPlanContentService.getById(planId).getStatus());
			maintainMalfunctionLog.setExecutor(executor);
			maintainMalfunctionLog.setTypeName(typeName + "[" + String.join("/", userNames) + "]");
			maintainMalfunctionLog.setUserNames(String.join("/", userNames));
			malfunctionLogService.save(maintainMalfunctionLog);
		}

	}

	/**
	 * 当前Service Map List转 Json String方法
	 */
	private String mapListToJson(List<Map<String, String>> listMap) {
		if (listMap == null || listMap.isEmpty()) {
			// 返回新的Json空串
			return JSON.toJSONString(new ArrayList<>());
		}
		return JSON.toJSONString(listMap);
	}

	/**
	 * 当前Service Json String转 Map List方法
	 *
	 * @param otherUrl 附件
	 * @return Map List
	 */
	private List<Map<String, String>> jsonToMapList(String otherUrl) {
		if (Func.isEmpty(otherUrl)) {
			return null;
		}
		return JSON.parseObject(otherUrl, new TypeReference<List<Map<String, String>>>() {
		});
	}


	/**
	 * 获取质检问题点的子工单信息
	 *
	 * @param planId 工单id
	 * @return 子工单信息
	 */
	@Override
	public CheckChildPlanVo getCheckChildPlanVo(Long planId) {
		List<Long> planIds = new ArrayList<>(10);
		planIds.add(planId);
		List<CheckChildPlanVo> list = baseMapper.getCheckChildPlanVo(planIds);
		for (CheckChildPlanVo checkChildPlanVo : list) {
			checkChildPlanVo.setStatusName(TaskStatusEnum.getTaskName(checkChildPlanVo.getTypeStatus(), checkChildPlanVo.getStatus()));
		}
		return list.get(0);
	}

	@Override
	public List<ProblemPlanVo> downProblemList(ProblemSearchVo problemSearchVo) {
		List<ProblemPlanVo> problemPlanVos = baseMapper.downProblemList(problemSearchVo);
		return problemPlanVos;
	}

	@Override
	public UserAffairAndCheckVo getPlanUserList(String userId) {
		UserAffairAndCheckVo userAffairAndCheckVo = new UserAffairAndCheckVo();
		MaintainPlanCheckPageDTO maintainPlanCheckDTO = new MaintainPlanCheckPageDTO();
		maintainPlanCheckDTO.setPlanUserId(userId);
		//表示离职人员
		Integer isUserStatus = 1;
		maintainPlanCheckDTO.setIsUserStatus(isUserStatus);
		List<MaintainPlanPageVO> maintainPlanPageVOS = baseMapper.pageByCondition(null, maintainPlanCheckDTO);
		List<MaintainPlanPageVO> list1 = maintainPlanPageVOS.stream().filter(o -> o.getPlanStatus() == TaskStatusEnum.ZJ_TO_START.getStatus() && o.getUserNames().split(",").length == 1).collect(Collectors.toList());
		List<MaintainPlanPageVO> list2 = maintainPlanPageVOS.stream().filter(o -> o.getPlanStatus() == TaskStatusEnum.ZJ_UNDER_WAY.getStatus() && o.getUserNames().split(",").length == 1).collect(Collectors.toList());
		userAffairAndCheckVo.setDisCounts(list1.size());
		userAffairAndCheckVo.setEnCounts(list2.size());
		userAffairAndCheckVo.setCounts(userAffairAndCheckVo.getDisCounts() + userAffairAndCheckVo.getEnCounts());
		return userAffairAndCheckVo;
	}

	@Override
	public List<MaintainPlanPageVO> getPlanListOfUserId(String userId) {
		MaintainPlanCheckPageDTO maintainPlanCheckDTO = new MaintainPlanCheckPageDTO();
		maintainPlanCheckDTO.setPlanUserId(userId);
		List<MaintainPlanPageVO> maintainPlanPageVOS = baseMapper.pageByCondition(null, maintainPlanCheckDTO);
		List<MaintainPlanPageVO> list = maintainPlanPageVOS.stream().filter(o -> (o.getPlanStatus() == TaskStatusEnum.ZJ_TO_START.getStatus() || o.getPlanStatus() == TaskStatusEnum.ZJ_UNDER_WAY.getStatus()) && o.getUserNames().split(",").length == 1).collect(Collectors.toList());
		return list;
	}
}
